#include <stdio.h>
#include <stdlib.h>
#include <gccore.h>
#include <string.h>
#include <wiiuse/wpad.h>
#include <ctype.h>

#define NOTVER

#include "libhttp.h"

void printdetails(client_t *client)
{
	printf("Method       : %s \r\n",client->request.method);
	printf("Path         : %s \r\n",client->request.path);
	printf("HTTP Version : %s \r\n",client->request.httpver);
	printf("Extension    : %s \r\n",client->request.extension);
	printf("MIME Type    : %s \r\n",client->response.mimetype);
}

int parserequest(char* request,bool debug,client_t *client)
{
	if(debug)
	{
		printf("Full request : %s \r\n",request);
	}
	char* method = "                                                     ";
	method = strtok(request," ");
	client->request.method = method;
	if(client->request.method[strlen(client->request.method)-1] == ' ')
	{
		return 0;
	}
	char* path = "                                                        ";
	path = strtok(NULL, " ");
	client->request.path = path;
	if(client->request.path[strlen(client->request.path)-1] == ' ')
	{
		return 0;
	}
	char* httpver = "                                                      ";
	httpver = strtok(NULL, "\r\n");
	client->request.httpver = httpver;
	client->response.httpver = httpver;
	if(client->request.httpver[strlen(client->request.httpver)-1] == ' ')
	{
		return 0;
	}
	char* body = "                                                      ";
	body = strtok(NULL, " ");
	client->request.body = body;
	if(client->request.body[strlen(client->request.body)-1] == ' ')
	{
		return 0;
	}
	if(debug)
	{
		printf("Method       : %s \r\n",method);
		printf("Path         : %s \r\n",path);
		printf("HTTP Version : %s \r\n",httpver);
	}
	char* extension = "                                            ";
	strcpy(extension,path);
	strtok(extension,".");
	extension = strtok(NULL,".");
	if(extension == NULL)
	{
		return 0;
	}
	client->request.extension = extension;
	if(debug)
	{
		printf("Extension    : %s \r\n",extension);
	}
	char* mimetype = "                                            ";
	int i;
	for(i = 0; extension[ i ]; i++)
    extension[i] = tolower(extension[ i ]);
	for (i = 0; builtin_mime_types[i].extension != NULL; i++) 
	{
		if ((strcmp(extension,builtin_mime_types[i].extension))==0)
		{
			strcpy(mimetype,builtin_mime_types[i].mime_type);
		}
	}
	client->response.mimetype = mimetype;
	if(debug)
	{
		printf("MIME Type    : %s \r\n",mimetype);
	}
	return 1;
}
